package Version4;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Response {

    private OutputStream outputStream;

    public Response() {
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }


    /**
     * Response 作为返回的对象，本就承载着返回数据到前端的功能
     * <p>
     * 这里仅仅是把字符串输出到输出流中
     *
     * @param content
     * @throws IOException
     */
    public void output(String content) throws IOException {
        this.outputStream.write(content.getBytes());
    }


    /**
     * 输出HTML
     * @param path index.html
     */
    public void outputHtml(String path) throws IOException {
        //得到html的绝对地址

        String absoluteResourcePath= StaticResourceUtil.getAbsolutePath(path);

        //把静态资源文件转换成文件，进行判断，存在则返回内容，不存在则返回404
        File file=new File(absoluteResourcePath);

        if(file.exists() && file.isFile()){
            //输出静态文件
            StaticResourceUtil.outputStaticResource(new FileInputStream(file),outputStream);
        }else{
            output(HttpProtocolUtil.getHttpHeader404());
        }


    }
}
